package me.fung.rem.app.rem_editor

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import me.fung.keen.app.view.View
import me.fung.rem.app.navigation
import me.fung.rem.app.settings.PAGE_TAG_VIEW
import me.fung.rem.bean.repo.RemItem
import me.fung.rem.bean.repo.tags
import me.fung.rem.common.PageState

const val PAGE_REM_EDITOR = "PAGE_MODIFY_REM"

class RemEditorView(
    private val data: RemItem?
) : View<RemEditorPresenter>() {

    var _showDialog = mutableStateOf(false)
    var _readOnly = mutableStateOf(p.pageState.value == PageState.BROWSE)

    @Composable
    override fun content(modifier: Modifier) {
        LaunchedEffect(Unit) {
            p.type.update { if (data == null) PageState.ADD else PageState.MODIFY }
            p.item.update { data ?: RemItem.sample().copy(del = false) }
            p.load()
        }
        editor(modifier)
        dialogToDel()
    }

    @Composable
    private fun editor(modifier: Modifier) {
        val type = remember { p.type }
        val pageState: PageState by remember { p.pageState }
        val readOnly: Boolean by remember { _readOnly }
        // 新添加时默认可编辑
        LaunchedEffect(Unit) {
            if (type.data == PageState.ADD) {
                p.pageState.value = PageState.ADD
            }
        }
        LaunchedEffect(pageState) {
            _readOnly.value = (pageState == PageState.BROWSE)
        }
        Box(
            modifier = modifier,
            contentAlignment = Alignment.Center
        ) {
            Row(
                modifier = Modifier.fillMaxSize().padding(horizontal = 5.dp),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Column(
                    modifier = Modifier.weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    if (pageState in listOf(PageState.ADD, PageState.MODIFY)) {
                        tagInfo(Modifier)
                    }
                }
                Column(
                    modifier = Modifier
                        .border(1.dp, color = Color.Black, shape = RoundedCornerShape(10.dp)).padding(20.dp)
                        .width(400.dp),
                ) {
                    Text(if (readOnly) "" else "正在编辑")
                    editorContent(Modifier)
                    buttons(Modifier)
                }
                Column(
                    modifier = Modifier.weight(1f),
                ) { }
            }

        }
    }
}


/**
 * 标签表中的标签
 */
@OptIn(ExperimentalMaterialApi::class, ExperimentalLayoutApi::class)
@Composable
fun RemEditorView.tagInfo(modifier: Modifier) {
    Column(modifier = modifier) {
        FlowRow(
            horizontalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            val ps by remember { p.pageState }
            val rp = remember { p }
            rp.tags.forEach {
                FilterChip(
                    selected = true,
                    onClick = {
                        rp.addTag(it)
                    },
                    leadingIcon = {
                        if (ps in listOf(PageState.ADD, PageState.MODIFY)) {
                            if (it.text in rp.item.data.tags()) {
                                Icon(Icons.Default.Check, null)
                            } else {
                                Icon(Icons.Default.Add, null)
                            }
                        } else {
                            Icon(Icons.Default.List, null)
                        }
                    }
                ) {
                    Text(text = it.text)
                }
            }
        }
        Button(onClick = { navigation.goto(PAGE_TAG_VIEW) }) { Text("管理标签") }
    }
}

/**
 * RemItem 的标签
 */
@OptIn(ExperimentalMaterialApi::class, ExperimentalLayoutApi::class)
@Composable
fun RemEditorView.tag(modifier: Modifier) {
    FlowRow(
        modifier = modifier,
        horizontalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        val rItem = remember { p.item }
        val rPageState = remember { p.pageState }
        Text(text="标签：",modifier = Modifier.padding(vertical = 15.dp))
        rItem.data.tags().forEach {
            FilterChip(
                selected = true,
                onClick = {
                    p.removeTag(it)
                },
                leadingIcon = {
                    if (rPageState.value in listOf(PageState.ADD, PageState.MODIFY)) {
                        Icon(Icons.Default.Clear, null)
                    } else {
                        Icon(Icons.Default.List, null)
                    }
                }
            ) {
                Text(text = it)
            }
        }
    }
}

@Composable
fun RemEditorView.editorContent(modifier: Modifier) {
    val item = remember { p.item }.data
    val readOnly: Boolean by remember { _readOnly }
    Column(modifier = modifier) {
        //
        OutlinedTextField(
            leadingIcon = { Icon(Icons.Default.List, "") },
            label = { Text("标题") },
            value = item.title,
            onValueChange = {
                p.update { copy(title = it) }
            },
            singleLine = true,
            readOnly = readOnly,
            modifier = Modifier.fillMaxWidth(),
        )
        //
        OutlinedTextField(
            leadingIcon = { Icon(Icons.Default.Person, "") },
            label = { Text("用户名") },
            value = item.username,
            onValueChange = {
                p.update { copy(username = it) }
            },
            singleLine = true,
            readOnly = readOnly,
            modifier = Modifier.fillMaxWidth(),
        )
        //
        var visual: Boolean by remember { mutableStateOf(false) }
        OutlinedTextField(
            leadingIcon = {
                Icon(Icons.Default.Lock, "")
            },
            trailingIcon = {
                IconButton(onClick = { visual = !visual }) {
                    Icon(Icons.Default.Info, "", modifier = Modifier)
                }
            },
            label = { Text("密码") },
            value = item.password,
            onValueChange = {
                p.update { copy(password = it) }
            },
            visualTransformation = if (visual) VisualTransformation.None else PasswordVisualTransformation(),
            singleLine = true,
            readOnly = readOnly,
            modifier = Modifier.fillMaxWidth(),
        )
        //
        OutlinedTextField(
            leadingIcon = { Icon(Icons.Default.Home, "") },
            label = { Text("地址") },
            value = item.address,
            onValueChange = { p.update { copy(address = it) } },
            singleLine = true,
            readOnly = readOnly,
            modifier = Modifier.fillMaxWidth(),
        )
        //
        OutlinedTextField(
            leadingIcon = { Icon(Icons.Default.List, "") },
            label = { Text("备注") },
            value = item.info,
            onValueChange = { p.update { copy(info = it) } },
            readOnly = readOnly,
            modifier = Modifier.fillMaxWidth(),
        )
        tag(Modifier)
    }
}

@Composable
fun RemEditorView.buttons(modifier: Modifier) {
    val type = remember { p.type }.data
    val readOnly: Boolean by remember { _readOnly }
    Row(modifier = modifier) {
        Button(
            onClick = { navigation.goBack() },
        ) { Text("返回") }
        if (type == PageState.MODIFY) {
            Spacer(modifier = Modifier.size(1.dp).weight(1f))
            Button(
                onClick = {
                    p.pageState.value = type
                },
                enabled = readOnly,

                ) {
                Text("编辑")
            }

            Spacer(modifier = Modifier.size(1.dp).weight(1f))
            Button(
                onClick = {
                    _showDialog.value = true
                },
                enabled = !readOnly
            ) {
                Text("删除")
            }
        }
        Spacer(modifier = Modifier.size(1.dp).weight(1f))
        Button(
            onClick = {
                p.pageState.value = PageState.BROWSE
                p.save()
            },
            enabled = !readOnly
        ) {
            Text("保存")
        }
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun RemEditorView.dialogToDel() {
    var showDialog by remember { _showDialog }
    if (showDialog) {
        Dialog(
            onDismissRequest = { showDialog = !showDialog },
        ) {
            Column(
                modifier = Modifier.background(MaterialTheme.colors.surface, RoundedCornerShape(5.dp)),
            ) {
                Column(
                    modifier = Modifier.padding(20.dp).align(Alignment.CenterHorizontally)
                ) {
                    Text(text = "确认删除\"${p.item.data.title}\"?")
                }

                Row(
                    modifier = Modifier,
                    horizontalArrangement = Arrangement.End
                ) {

                    CompositionLocalProvider(LocalMinimumInteractiveComponentEnforcement provides false) {
                        Button(
                            onClick = {
                                p.delete()
                                navigation.goBack()
                            },
                            modifier = Modifier.weight(1f),
                            shape = RoundedCornerShape(0.dp),
                        ) { Text("确认") }
                        Spacer(modifier = Modifier.size(1.dp))
                        Button(
                            onClick = { showDialog = !showDialog },
                            modifier = Modifier.weight(1f),
                            shape = RoundedCornerShape(0.dp),
                        ) { Text("取消") }
                    }
                }
            }
        }
    }
}

